import { Table, Modal, message, Select, Form, Input, Button } from 'antd';
import React, { useEffect, useState, useRef } from 'react';
import { columns } from '@/utils/config/storyConfig';
import type { ColumnsType } from 'antd/es/table';
import { colWidth } from '@/utils/tools';
import { useRouter } from 'next/router';
import { storyOptions } from '@/utils/data';
import { story_list, updateStoryApi } from '@/request/story';
import usePagination, { useHeight } from '@/utils/hooks/pagination';
import PageTitle from '@/components/pageTitle';
import StorySearch from './search';
import RelationProject from './components/relationProject';

interface DataType {
  fixed: string | undefined;
}

const Index = () => {
  const [searchParams, setSearchParams] = useState({});
  const scrollRef = useRef<any>(null);
  const [list, setList] = useState<any[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [statusDialog, setStatusDialog] = useState(false);
  const [form] = Form.useForm();
  const router = useRouter();
  const relationProject = useRef<any>(null);
  const { pagination, setPagination, onChange } = usePagination({
    pageSize: 10,
  });
  const { height } = useHeight(300);
  const handleSearch = async (params) => {
    try {
      setLoading(true);
      const ret: any = await story_list(params);
      if (ret) {
        setList(ret.data);
        setPagination({
          ...pagination,
          total: ret.total,
        });
      }
    } catch (err: any) {
      console.log(err);
    } finally {
      setLoading(false);
    }
  };

  const handleChange = (page: any) => {
    onChange(page);
    handleSearch({
      ...searchParams,
      page: page.current,
      pageSize: page.pageSize,
    });
  };

  const handleFinish = (value: any) => {
    setPagination({
      ...pagination,
      current: 1,
      pageSize: pagination.pageSize,
    });
    setSearchParams(value);
  };

  const handleReset = () => {
    setSearchParams({});
  };

  useEffect(() => {
    handleSearch({ ...searchParams, page: 1, pageSize: pagination.pageSize });
  }, [searchParams]);

  const onOkCallback = () => {
    handleSearch({ ...searchParams, page: pagination.current, pageSize: pagination.pageSize });
  };

  const handleEdit = ({ id }) => {
    router.push(`/storyManage/edit/${String(id)}`);
  };

  // 关联项目
  const handleRelation = (record) => {
    relationProject.current.handleOpen(record);
  };
  // 修改需求状态
  const handleChangeStatus = (record) => {
    setStatusDialog(true);
    form.setFieldsValue({
      id: record.id,
      status: record.status,
    });
  };
  // 操作
  const handleOperation = (type, record) => {
    if (type === 'edit') {
      handleEdit(record);
    } else if (type === 'relation') {
      handleRelation(record);
    } else if (type === 'status') {
      handleChangeStatus(record);
    }
  };

  // 修改状态弹框提交
  const handleStatusDialogOk = async () => {
    const data = form.getFieldsValue();
    try {
      const res: any = await updateStoryApi({ ...data, object_type: 'story' });
      if (res) {
        message.success('保存成功');
        setStatusDialog(false);
        handleSearch(searchParams);
      } else {
        message.error('保存失败');
      }
    } catch (err: any) {
      console.log(err.message);
    }
  };
  const myColumns = columns(handleOperation);

  return (
    <div ref={scrollRef}>
      <PageTitle title="需求列表" />
      <StorySearch handleFinish={handleFinish} handleReset={handleReset} />
      <Table
        columns={myColumns as ColumnsType<DataType>}
        dataSource={list}
        rowKey="id"
        scroll={{ x: colWidth(myColumns), y: height }}
        loading={loading}
        onChange={handleChange}
        pagination={pagination}
      ></Table>
      {/* 变更状态 */}
      <Modal
        open={statusDialog}
        onOk={() => {
          handleStatusDialogOk();
        }}
        onCancel={() => {
          setStatusDialog(false);
        }}
      >
        <Form form={form}>
          <Form.Item label="id" name="id" hidden>
            <Input />
          </Form.Item>
          <Form.Item label="需求状态" name="status">
            <Select options={storyOptions} placeholder="请选择" style={{ width: '200px' }}></Select>
          </Form.Item>
        </Form>
      </Modal>
      {/* 关联项目 */}
      <RelationProject ref={relationProject} onOkCallback={onOkCallback} />
    </div>
  );
};

export default Index;
